package com.hfb.mashibing.alip8.system.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

public class T01_BIO_SocketIO {

    public static void main(String[] args) throws IOException {
        // 起一个监听
        ServerSocket socket = new ServerSocket(8090, 20);
        System.out.println("step1: new ServerSocket(8090)");

        while (true) {
            Socket client = socket.accept(); // 接收服务是阻塞的， 阻塞1
            System.out.println("step2: client \t" + client.getPort());

            new Thread(new Runnable() {
                Socket so;
                public Runnable setSo(Socket so) {
                    so = so;
                    return this;
                }
                @Override
                public void run() {
                    try(InputStream in = so.getInputStream();
                        BufferedReader reader = new BufferedReader(
                                                    new InputStreamReader(in))) {

                        while (true) {
                            System.out.println(reader.readLine()); // 读数据也是阻塞的，阻塞2
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.setSo(client)).start();

        }

    }

}
